
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-if="checkPermission(['newadd'])" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="70"
      >
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="无事故天数" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="无事故时间" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="无事故开始时间" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="基数" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="当日无事故天数" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上月20号无事故天数" width="130">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上月20号无事故时间数" width="130">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发生事故时间" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="长期目标" width="80">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="短期目标" width="80">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="6个月到达时间" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="事故描述" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="录入人" width="80">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="录入时间" width="100">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(['newedit'])" type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="checkPermission(['newdel'])" type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageQ" :limit.sync="listQuery.limit" @pagination="fechData" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item label="ID" prop="id">
          <el-input v-model="temp.id" readonly />
        </el-form-item>
        <!--  <el-form-item label="受训人" prop="trainee">
          <el-select v-if="temp.id>0" v-model="userNameE" class="filter-item" placeholder="请选择">
            <el-option v-for="item in personlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="受训人">
          <el-autocomplete
            v-model="userIdE"
            class="el-input"
            :fetch-suggestions="userSearchAsyncE"
            placeholder="请输入工号"
            :trigger-on-focus="false"
            @select="handleSelectE"
          />
        </el-form-item>
        <el-form-item label="所属Team" prop="deptId">
          <el-select v-model="deptName1" class="filter-item" placeholder="请选择">
            <el-option v-for="item in deptlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="培训级别" prop="levels">
          <el-select v-model="temp.levels" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="主题" prop="subject">
          <el-input v-model="temp.subject" />
        </el-form-item>
        <el-form-item label="培训开始时间" prop="sdate">
          <el-date-picker v-model="temp.sdate" type="date" />
        </el-form-item>
        <el-form-item label="培训结束时间" prop="edate">
          <el-date-picker v-model="temp.edate" type="date" />
        </el-form-item>
        <el-form-item label="学时" prop="period">
          <el-input v-model="temp.period" />
        </el-form-item>
        <el-form-item label="分数" prop="grade">
          <el-input v-model="temp.grade" />
        </el-form-item>
        <el-form-item label="培训人">
          <el-autocomplete
            v-model="userIdR"
            class="el-input"
            :fetch-suggestions="userSearchAsyncR"
            placeholder="请输入工号"
            :trigger-on-focus="false"
            @select="handleSelectR"
          />
        </el-form-item>
        <el-form-item label="培训内容" prop="content">
          <el-input v-model="temp.content" type="textarea" />
        </el-form-item>
        <el-form-item label="审核人">
          <el-autocomplete
            v-model="userIdA"
            class="el-input"
            :fetch-suggestions="userSearchAsyncA"
            placeholder="请输入工号"
            :trigger-on-focus="false"
            @select="handleSelectA"
          />
        </el-form-item>
        <el-form-item label="审核意见" prop="auditinf">
          <el-input v-model="temp.auditinf" type="textarea" readonly />
        </el-form-item>
        <el-form-item label="审核时间" prop="odate">
          <el-date-picker v-model="temp.odate" type="date" readonly />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { fetchTrainNewList, createTrainNew, editTrainNew, getDeptList } from '@/api/trainNew'
import Sortable from 'sortablejs'
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { getuserbyemp } from '@/api/user'
import checkPermission from '@/utils/permission'
export default {
  name: 'TrainNew',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      editList: null,
      sortable: null,
      deptName1: null,
      userIdE: '',
      userIdR: '',
      userIdA: '',
      oldList: [],
      newList: [],
      addArr: null,
      addFileName: null,
      resetAdd: null,
      addName: null,
      dialogAddFile: null,
      // 参数条件
      listQuery: {
        pageQ: 1,
        limit: 20,
        lsdate: null,
        ledate: null,
        traineeName: null
      },
      // personlist: null,
      deptlist: null,
      options: [{ value: 1, label: '入厂培训' }, { value: 2, label: '车间培训' }, { value: 3, label: '班组培训' }],

      temp: {
        id: undefined,
        sdate: new Date(),
        edate: new Date(),
        ldate: null,
        subject: '',
        trainer: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '创建',
        detail: '明细'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'sdate', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.fechData()
  },
  methods: {
    fechData() {
      getDeptList().then(response => {
        this.deptlist = response.deptlist
      })
      /* fetchAllCount().then(response => {
        this.total = response.count
      }) */
      fetchTrainNewList(this.listQuery).then(response => {
        this.listLoading = true
        this.list = response.ehstrainnewList
        this.showList = response.ehstrainnewList
        this.listLoading = false
        this.total = response.count
      })
    },

    checkPermission,
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const deptName1 = this.deptName1
          const userIdE = this.userIdE
          const userIdR = this.userIdR
          const userIdA = this.userIdA
          const query =
          {
            deptName1: deptName1,
            userIdE: userIdE,
            userIdR: userIdR,
            userIdA: userIdA,
            subject: this.temp.subject,
            levels: this.temp.levels,
            sdate: this.temp.sdate,
            edate: this.temp.edate,
            period: this.temp.period,
            grade: this.temp.grade,
            content: this.temp.content,
            ldate: this.temp.ldate }
          createTrainNew(query).then(() => {
            this.list.unshift(this.temp.userNameE)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            location.reload()
          })
        }
      })
    },
    // 受训人
    async userSearchAsyncE(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName
        tem_obj.userId = r.userId
        list.push(tem_obj)
      })

      callback(list)
    },
    async handleSelectE(u) {
      this.userIdE = u.userId + ''
    },
    // 培训人
    async userSearchAsyncR(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName
        tem_obj.userId = r.userId
        list.push(tem_obj)
      })

      callback(list)
    },
    async handleSelectR(u) {
      this.userIdR = u.userId + ''
    },
    // 审核人
    async userSearchAsyncA(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName
        tem_obj.userId = r.userId
        list.push(tem_obj)
      })

      callback(list)
    },
    async handleSelectA(u) {
      this.userIdA = u.userId + ''
    },
    handleFilter() {
      this.listQuery.pageQ = 1
      this.fechData()
    },
    handleEdit(row) {
      /* getPersonList().then(response => {
        this.personlist = response.personlist
      }) */
      /* getDeptList().then(response => {
        this.deptlist = response.deptlist
      }) */

      const row1 = JSON.parse(JSON.stringify(row))
      this.temp1 = Object.assign({}, row1) // copy obj

      this.deptName1 = this.temp1.deptid.deptName
      this.userIdE = this.temp1.trainee.userName
      this.userIdR = this.temp1.trainer.userName
      // this.userIdA = this.temp1.auditor.userName
      this.temp.subject = this.temp1.subject
      this.temp.levels = this.temp1.levels
      this.temp.sdate = this.temp1.sdate
      this.temp.edate = this.temp1.edate
      this.temp.period = this.temp1.period
      this.temp.grade = this.temp1.grade
      this.temp.content = this.temp1.content
      this.temp.ldate = this.temp1.ldate
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (this.dialogStatus === 'detail') {
        location.reload()
      } else if (this.dialogStatus === 'update') {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            const query1 = JSON.parse(JSON.stringify(tempData))
            tempData.data = +new Date(tempData.data) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            const query =
            { id: query1.id,
              subject: query1.subject,
              levels: query1.levels,
              userIdE: this.userIdE,
              userIdR: this.userIdR,
              userIdA: this.userIdA,
              deptName1: this.deptName1,
              sdate: query1.sdate,
              edate: query1.edate,
              period: query1.period,
              grade: query1.grade,
              content: query1.content,
              ldate: query1.ldate }
            editTrainNew(query).then(response => {

            })
            // 刷新页面
            location.reload()
          }
        })
      }
    },
    handleDetail(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1) // copy obj

      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    setSort() {
      const el = this.list[0]

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
</style>
